import {HttpConfig, HttpResponse} from "./httpConfig"
import {goLogin} from "../tools/go"
import {toast} from "../components/popup/popup"
import {getToken} from "../store/index"
import {mod} from "../main"
const url = [
    "http://192.168.29.3:8080",
    "http://127.0.0.1:8080",
    "http://192.168.29.3:8080"
]

const baseUrl = mod === "development" ? url[1] : url[2]


const afterRequest = (res:any) :HttpResponse => {

    console.log(res)


    return res.data
}


const request = (config:HttpConfig) :Promise<HttpResponse> => {

    let requestUrl = baseUrl + config.url

    if (config["httpOptions"].token) {
        if (getToken() === null) {
            toast("请先登录", "error")
            goLogin()
        }
        config.headers.auth = getToken()
    }

    return new Promise((resolve, reject) => {
        // @ts-ignore
        uni.request({
            url: requestUrl,
            method: config.method,
            data: config.data,
            header: config.headers,
            dataType: "json",
            getResponse: true,
            success: (res) => {
                resolve(afterRequest(res))
            },
            fail: (err) => {
                reject(err)
            }
        })
    })
}

export default request